package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.autoconfig.aip.AipFaceTemplate;
import com.itheima.autoconfig.im.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {

    @DubboReference
    UserService userService;

    @Autowired
    SmsTemplate smsTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    AipFaceTemplate aipFaceTemplate;

    @Autowired
    OssTemplate ossTemplate;

    @Autowired
    HuanXinTemplate huanXinTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    public Long save(User user){
        //设置一个初始化密码
        user.setPassword(ConstantUtil.INIT_PASSWORD);

        return userService.save(user);
    }

    public User findByMobile(String mobile){
        return userService.findByMobile(mobile);
    }

    public void sendCode(String phone) {
        //1.生成随机验证码(6位数字)-使用hutool
        String code = RandomUtil.randomNumbers(6);
        //TODO 为了开发简单,发送固定的验证码"123456",等项目上线了,在发送随机
        code = "123456";

        //2.调用smsTemplate发送验证码
        //TODO 项目上线了再把这行代码打开
        //smsTemplate.sendSms(phone,code);

        //3.将验证码存入redis中,且设置时效5分钟
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE+phone,code, Duration.ofMinutes(5));
    }

    public ResponseEntity regAndLogin(Map<String, String> map) {
        //1.获取手机号和验证码
        String phone = map.get("phone");
        String verificationCode = map.get("verificationCode");

        //2.判断验证码和redis中是否相同,若不相同返回错误提示
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        String redisCode = operations.get(ConstantUtil.SMS_CODE + phone);

        //使用hutools
        if (!StrUtil.equals(verificationCode,redisCode)) {
            //return ResponseEntity.status(500).body("请输入正确的验证码");
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }

        //3.远程调用service,查询手机号是否存在
        User user = userService.findByMobile(phone);

        boolean isNew;
        //3.1 若存在 isNew=false
        if (user != null) {
            isNew = false;
        }else {
            //3.2 若不存在 isNew=true,封装user数据,保存到数据库中
            isNew = true;

            user = new User();
            user.setMobile(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);

            Long id = userService.save(user);
            //别忘记给用户设置id
            user.setId(id);

            //往环信上注册下
            huanXinTemplate.register("HX"+id);
        }

        //4.准备用户数据(id,手机号),生成token
        Map<String,Object> userMap = new HashMap<>();
        userMap.put("id",user.getId());
        userMap.put("mobile",user.getMobile());

        String token = JwtUtil.createToken(userMap);

        //5.以后用户每次请求过来的时候都需要解析token,获取用户信息,有点麻烦,为了减少麻烦,token作为key,user的json字符串作为value存入redis中,设置时效30天
        operations.set(ConstantUtil.USER_TOKEN+token, JSON.toJSONString(user),Duration.ofDays(30));

        //6.准备返回的数据(map),且返回
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("token",token);
        resultMap.put("isNew",isNew);

        //7.可以不写,建议把验证码删除一下
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE+phone);

        //8.封装日志对象,发送到mq中
        Log log = new Log();
        log.setUserId(user.getId());
        log.setLogTime(DateUtil.formatDate(new Date()));
        log.setPlace("合肥闽商国贸");
        log.setEquipment("华为p70");
        //设置用户行为
        log.setType(isNew?"0102":"0101");
        //发送mq
        rabbitTemplate.convertAndSend("tanhua.log",log);

        return ResponseEntity.ok(resultMap);
    }

    public ResponseEntity saveUserInfo(UserInfo userInfo, String token) {
        //1.从token中获取当前登陆者
        User user = getUserFromToken(token);

        //2.判断登陆者是否为空,若为空返回401
        if (user == null) {
            return ResponseEntity.status(401).body(null);
        }

        //3.获取用户id,设置给userInfo
        userInfo.setId(user.getId());

        //4.远程service完成保存操作
        userInfoService.save(userInfo);
        return ResponseEntity.ok(null);
    }

    //从token中获取用户信息
    public User getUserFromToken(String token) {
        if (StrUtil.isNotBlank(token)) {
            String jsonStr = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

            if (StrUtil.isNotBlank(jsonStr)) {
                return JSON.parseObject(jsonStr,User.class);
            }
        }

        return null;
    }

    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, String token) throws IOException {
        //1.通过token获取用户
        //User user = getUserFromToken(token);
        //2.判断用户是否存在,若不存在返回401
        //if (user == null) {
        //    return ResponseEntity.status(401).body(null);
        //}
        User user = UserHolder.get();

        //3.先判断头像是否为人脸,若不是返回错误
        if (!aipFaceTemplate.detect(headPhoto.getBytes())) {
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }

        //4.将用户头像保存到oss上,返回url
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //5.创建一个UserInfo,设置id和头像
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId());
        userInfo.setAvatar(url);//头像
        userInfo.setCoverPic(url);//封面

        //6.远程调用service完成更新操作
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity findUserInfoById(Long id) {
        //1.远程调用service查询userInfo
        UserInfo userInfo = userInfoService.findById(id);

        //2.创建userInfoVo对象
        UserInfoVo vo = new UserInfoVo();

        //3.属性拷贝(我使用hutool中提供的工具类--参数1:有数据的对象,参数2:目标对象)
        BeanUtil.copyProperties(userInfo,vo);

        //4.返回userInfoVo
        return ResponseEntity.ok(vo);
    }

    public ResponseEntity updateUserInfo(UserInfo userInfo, String token) {
        //1.通过token获取用户
        //User user = getUserFromToken(token);
        //2.判断用户是否存在,若不存在返回401
        //if (user == null) {
        //    return ResponseEntity.status(401).body(null);
        //}
        User user = UserHolder.get();

        //3.若用户存在,给userInfo去设置id
        userInfo.setId(user.getId());

        //4.远程调用service完成更新操作
        userInfoService.update(userInfo);
        return ResponseEntity.ok(null);
    }
}
